package mall.demo.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import mall.demo.crawl.DdSearchCrawler;
import mall.demo.crawl.ICrawler;
import mall.demo.crawl.JdSearchCrawler;
import mall.demo.mybatis.pojo.Product;
import mall.demo.util.CrawlType;
import mall.demo.util.RequestKeyEnum;
import mall.demo.util.SessionKeyEnum;

/**
 * Servlet implementation class ProductCrawlerServlet
 */
@WebServlet("/servlet/crawl")
public class ProductCrawlerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static Logger logger = LoggerFactory.getLogger(ProductCrawlerServlet.class);
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ProductCrawlerServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
//		response.getWriter().append("Served at: ").append(request.getContextPath());
		request.setCharacterEncoding("UTF-8");
		String type  = request.getParameter("targetType");
		String url = request.getParameter("targetUrl");
		logger.info("type=" + type + ",url=" + url);
		ICrawler crawler = null;
		if (CrawlType.JDSEARCH.equals(type)) {
			crawler = new JdSearchCrawler(url);
			crawler.setProperties(null);
		} else if(CrawlType.DDSEARCH.equals(type)) {
			crawler = new DdSearchCrawler(url);
			crawler.setProperties(null);
		}
		if(crawler != null) {
			List<Product> products = crawler.crawl();
			request.getSession().setAttribute(SessionKeyEnum.crawlProducts.name(), products);
			request.getRequestDispatcher("/admin/crawlerResult.jsp").forward(request, response);
			return;
		} else {
			response.getWriter().println("not support type " + type);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
